<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Controllers\Api\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends BaseController {

	public function upload(Request $request) {
		$file = $request->file('file');
		if ($file->isValid()) {
			$ext = $file->getClientOriginalExtension();
			$real_path = $file->getRealPath();
			$type = $file->getClientMimeType();
			$file_name = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
			$disk_type = $this->getType($request);
			$bool = Storage::disk($disk_type)->put($file_name, file_get_contents($real_path));
			if (!$bool) {
				abort(500, 'file move fail');
			}
			$file_path = asset('storage/' . $disk_type . 's/' . $file_name);
			return $this->response->withSuccess($file_path);
		} else {
			abort(422, 'file upload fail');
		}
	}

	private function getType(Request $request) {
		$type = $request->type;
		if (!$type || !in_array($type, ['note', 'item', 'carousel', 'avatar', 'wechat'])) {
			abort(422, 'not allow image upload type');
		}
		return $type;
	}
}
